﻿using Microsoft.AspNetCore.Mvc;
using RTW.Core.Controllers;
using RTW.Model;
using RTW.Servers;
using System.Data;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace RTW.Web.Areas.Unit.Controllers
{
    [Area("Unit")]
    public class RoleController : BaseController 
    {
        public int Expiration { get; set; } = 5;

        DataTable dt = new DataTable();

        public UnitServers unitservers;
        public UserServers userservers;
        public DeptServers deptservers;
        public RoleServers roleservers;
        public UserRoleserver UserRoleserver;
        public Userlistserver userlistserver;
        public HomeMenuServer HomeMenuServer;
        public  RoleController()
        {
            unitservers = new UnitServers();
            userservers = new UserServers();
            deptservers = new DeptServers();
            roleservers = new RoleServers();
            UserRoleserver = new UserRoleserver();
            userlistserver = new Userlistserver();
            HomeMenuServer = new HomeMenuServer();
        }
        public IActionResult Index()
        {
            return View();
        }

        public  IActionResult ManageTable()
        {
            return View();
        }

        public async Task<IActionResult> GetManageTableJson()
        {
            var mtj = ListResult < SysHomeMenu > (await HomeMenuServer.GetAll());
            return Json(mtj);
        }
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();  //注意 要有T类型要有无参构造函数
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
        [HttpPost]
        public async Task<IActionResult> PostManageTableJson(string data)
        {
            JArray jo = (JArray)JsonConvert.DeserializeObject(data);
            int a = 0;
            foreach (var item in jo)
            {
                JObject jdata = (JObject)item;
                SysHomeMenu sysHomeMenu = new SysHomeMenu();
                sysHomeMenu.HMID =Convert.ToInt32(jdata["hmid"]);
                sysHomeMenu.HMMC = jdata["hmmc"].ToString();
                sysHomeMenu.DWID = Convert.ToInt32(jdata["dwid"]);
                sysHomeMenu.HMZT = jdata["hmzt"].ToString();
                sysHomeMenu.HMBZ = jdata["hmbz"].ToString();
                sysHomeMenu.HMLJ = jdata["hmlj"].ToString();
                sysHomeMenu.HMTX = jdata["hmtx"].ToString();
                sysHomeMenu.HMSX = jdata["hmsx"].ToString();
                sysHomeMenu.HMYS = jdata["hmys"].ToString();
                a= await HomeMenuServer.Edit(sysHomeMenu);
            }
            return Json(MsgResult(a == 1));
        }

        static public T DeserializeJSON<T>(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }


        public IActionResult Role(string name)
        {
            ViewData["KindsType"] = name;
            return View();
        }


        /// <summary>
        /// From表单的绑定
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult>  RoleFrom(int? yhid,string type,string DWID,string KindsType)
        {
            Manage manage = new Manage();
            manage.Dept = await deptservers.GetDeptIDWhere(yhid);
            manage.Role = await roleservers.GetRoleIDWhere(yhid);
            manage.User = await userservers.GetUserIDWhere(yhid);

            if (KindsType == "User")
            {
                foreach (var item in await UserRoleserver.GetUserRoleID(yhid))
                {
                    ViewData["CheackRoleFrom"] = item.RID;
                    ViewData["UserRoleID"] = item.ID;
                }
            }
            
            ViewBag.rolelist = new MultiSelectList(await roleservers.GetAll(), "RID","RMC");

            ViewBag.deptlist = new MultiSelectList(await deptservers.GetDeptSelect(), "BMID", "BMMC");

            
            ViewData["dwid"] = DWID;
            ViewData["type"] = type;
            ViewData["KindsType"] = KindsType;

            return View(manage);
        }

        /// <summary>
        /// 添加和编辑操作
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> RoleFrom(SysUser su, SysDept dept, SysRole role ,SysUserRole userRole, string type,string KindsType)
        {
            if (KindsType == "User")
            {
                if (su != null)
                {
                    if (type == "add")
                    {
                        su.TJSJ = DateTime.Now.ToString();//添加时间
                        su.QID = su.QID == null ? 0 : 1;//权限
                        su.YHZT = su.YHZT == null ? "0" : "1";//用户状态
                        userRole.RID = role.RID;

                        bool flag = await userservers.AnyByName(su.YHMC);
                        if (flag)
                            return Json(Failed("用户名已存在！"));

                        int b = await userservers.Add(su);

                        foreach (var item in await userservers.GetUserID(su.YHMC))
                        {
                            userRole.YHID = item.YHID;                    
                        }
                        int u=await UserRoleserver.Add(userRole);

                        return Json(MsgResult(u == 1));
                    }
                    else if (type == "edit")
                    {
                        su.QID = su.QID == null ? 0 : 1;
                        su.YHZT = su.YHZT == null ? "0" : "1";

                        foreach(var item in await UserRoleserver.GetUserRoleID(su.YHID))
                        {
                            userRole.ID = item.ID;
                        }
                        int a = await UserRoleserver.Edit(userRole);
                        int b = await userservers.Edit(su);
                        return Json(MsgResult(b == 1));
                    }
                }
                return View(su);
            }
            else if (KindsType == "Dept")
            {
                if (dept != null)
                {
                    if (type == "add")
                    {
                        dept.BMTJSJ = DateTime.Now.ToString();//添加时间
                        dept.BMZT = dept.BMZT == null ? "0" : "1";//用户状态
                        bool flag = await deptservers.AnyByName(dept.BMMC);
                        if (flag)
                            return Json(Failed("此部门已存在！"));
                        int b =  await deptservers.Add(dept);

                        return Json(MsgResult(b == 1));
                    }
                    else if (type == "edit")
                    { 
                        dept.BMZT = dept.BMZT == null ? "0" : "1";//用户状态
                        int b = await deptservers.Edit(dept);
                        return Json(MsgResult(b == 1));
                    }
                }
                return View(dept);
            }
            else if (KindsType == "Role")
            {
                if (role != null)
                {
                    if (type == "add")
                    {
                        role.RTJSJ = DateTime.Now.ToString();
                        bool flag = await roleservers.AnyByName(role.RMC);
                        if (flag)
                            return Json(Failed("此身份已存在！"));
                        int b = await roleservers.Add(role);

                        return Json(MsgResult(b == 1));
                    }
                    else if (type == "edit")
                    {
                        int b = await roleservers.Edit(role);
                        return Json(MsgResult(b == 1));
                    }
                }
                return View(role);
            }
            //绑定父级机构列表

            return View();
        }

        [HttpPost]
        public async Task<IActionResult> del(string yhid,string KindsType)
        {
            int res =1;
            if (KindsType == "User")
            {
                int usroledel = await UserRoleserver.Del(yhid);
                res = await userservers.Del(yhid);
            }
            else if (KindsType == "Dept")
                res = await deptservers.Del(yhid);
            else if (KindsType == "Role")
                res = await roleservers.Del(yhid);
            return Json(res > 1);
        }

        public async Task<IActionResult> GetAllDtreeJson()
        {
            var res = await unitservers.GetAllUnits();
            return Json(ListResult<SysUnit>(res));
        }

        public async Task<IActionResult> GetAllDateJson(int? dwid,string kindsType)
        {
            var res=new object();
            if (kindsType == "User") {
                res = ListResult<SysUserlist>(await userlistserver.GetUserWhere(dwid));
            }
            else if (kindsType == "Dept")
                res = ListResult<SysDept>(await deptservers.GetDeptWhere(dwid));
            else if (kindsType == "Role")
                res = ListResult<SysRole>(await roleservers.GetRoleWhere(dwid));
            return Json(res);
        }
    }
}